#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <time.h>
#include <stdint.h>
#include <sys/time.h>

#include "mixer_scale.h"

#include "debug/debug.h"

static struct mixer_scale_param {
    int mixer_fb;
    int rmem_fb;
    struct  mixer_scale_in_param in_param;
    struct  mixer_scale_out_param out_param;
}scale_param;

int mixer_scale_out_init_param(struct mixer_scale_out_param* out_param)
{
    int ret = -1;

    memcpy(&scale_param.out_param, out_param, sizeof(struct mixer_scale_out_param));
    scale_param.mixer_fb = fb_layer_mixer_create(&scale_param.out_param.cfg);
    if (scale_param.mixer_fb < 0)
    {
        print_error("fb layer mixer create faild.");
        return ret;
    }

    return 0;
}

void mixer_scale_out_uninit(void)
{
    if(scale_param.mixer_fb > 0)
        fb_layer_mixer_delete(scale_param.mixer_fb);
}

int mixer_scale_update_in_param(struct video_frame* frame)
{
    int ret = -1;
    struct lcdc_layer layer = {
        .fb_fmt = fb_fmt_NV12,
        .xres = frame->width,
        .yres = frame->height,
        .xpos = 0,
        .ypos = 0,

        .layer_order = lcdc_layer_0,
        .layer_enable = 1,

        .y = {
            .mem = (void*)frame->phys_data[0],
            .stride = frame->linesize[0],
        },
        .uv = {
            .mem = (void*)frame->phys_data[1],
            .stride = frame->linesize[1],
        },

        .alpha = {
            .enable = 1,
            .value = 0xff,
        },
        .scaling = {
            .enable = 1,
            .xres = scale_param.out_param.cfg.xres,
            .yres = scale_param.out_param.cfg.yres,
        },
    };

    if (scale_param.mixer_fb <= 0)
    {
        print_error("scale_param.fb didn't init.");
        return ret;
    }

    ret = fb_layer_mixer_set_input_layer(scale_param.mixer_fb, 0, &layer);
    if (ret) {
        print_error("fb_layer_mixer_set_input_layer:  fail.");
        return ret;
    }

    return ret;
}

int mixer_scale_work_out_one_frame(void)
{
    int ret = -1;

    if (scale_param.mixer_fb <= 0)
        return ret;

    ret = fb_layer_mixer_work_out_one_frame(scale_param.mixer_fb);
    if (ret) {
        print_error("fb_layer_mixer_work_out_one_frame: fail.");
    }

    return ret;
}